package com.peng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.common.R;
import com.peng.entity.User;
import com.peng.service.UserService;
import com.peng.utils.SMSUtils;
import com.peng.utils.ValidateCodeUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户控制层")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("发短信")
    @ApiImplicitParams({@ApiImplicitParam(name = "user",value = "手机号",required = true)})
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)){

            String code = ValidateCodeUtils.generateValidateCode(4).toString();
//            SMSUtils.sendMessage("邓鹏个人学习使用","1417754","86"+phone,code);
            log.info("发送了->{}",code);
//            session.setAttribute(phone,code);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        }
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map map, HttpSession session){
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
//        String attribute = (String) session.getAttribute(phone);
        String attribute= (String) redisTemplate.opsForValue().get(phone);
        if (code.equals(attribute)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(userLambdaQueryWrapper);
            if (user==null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            redisTemplate.delete(phone);
            R.success("登录成功");
        }
        System.out.println(map);
        return R.success("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
